package edu.utsa.cs.contactmanager.views;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import edu.utsa.cs.contactmanager.Contact;
import edu.utsa.cs.contactmanager.ContactManager;
import edu.utsa.cs.contactmanager.Group;
import edu.utsa.cs.contactmanager.OnTaskCompleted;
import edu.utsa.cs.contactmanager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class View_Group extends ListActivity implements OnTaskCompleted{
	
	Group group;
	
	ArrayList<String> names;
    TreeMap<String, Contact> hm;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_single_group);
        Intent i = getIntent();
        group = (Group)i.getSerializableExtra("group");
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.view_group, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_remove:
            delete();
            return true;
        case R.id.action_add:
        	addMember();
        	return true;
        case R.id.action_remove_member:
        	removeMember();
        	return true;
        case R.id.action_change_name:
        	changeName();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    private void resetView(){
    	ArrayList<Long> ids = new ArrayList<Long>();
    	
		Intent i = getIntent();
		
		group = ContactManager.getGroups(group.getID()).get(0);
		
		setContentView(R.layout.activity_view_single_group);
		
		List<Contact> members = group.getMembers();
		for(Contact c : members){
			ids.add(c.getID());
		}       
	    
		names = new ArrayList<String>();
        hm = new TreeMap<String, Contact>();
                
	    ArrayList<Contact> contactsFound = ContactManager.getContacts(ids.toArray(new Long[0]));

        if(contactsFound == null || contactsFound.isEmpty()){
            TextView t = (TextView)findViewById(R.id.title);
            t.setText("Group \"" + group.getName() + "\" does not have any members. Please add a member.");
        }
        else{
            String name;
            
            Iterator<Contact> iter = contactsFound.iterator();
            Contact contact;
            
            TextView t = (TextView)findViewById(R.id.title);
            t.setText("Viewing group \"" + group.getName() + "\"");
            
            while(iter.hasNext()){
            	contact = iter.next();
                name = contact.getFirstName() + " " + contact.getLastName();
                names.add(name);
                hm.put(name, contact);
            }
            
            
        }
        //Display list adapter
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names));
	}
	
	@Override
    protected void onListItemClick(ListView list, View view, int position, long id){
        super.onListItemClick(list, view, position, id);
        Contact contact = hm.get(names.get(position));
        
        Intent i = new Intent(this, View_SingleContact.class);
        i.putExtra("contact", contact);
        startActivity(i);
    }
	
	@Override
    public void onResume(){
    	ContactManager.open();
    	resetView();
    	super.onResume();
    };
    
    @Override
    public void onPause(){
    	ContactManager.close();
    	super.onPause();
    }
    
    private void changeName(){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Enter name for new group.");
    	final OnTaskCompleted callback = this;
    	// Set up the input
    	final EditText input = new EditText(this);
    	// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
    	input.setInputType(InputType.TYPE_CLASS_TEXT);
    	builder.setView(input);

    	// Set up the buttons
    	builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    	    @Override
    	    public void onClick(DialogInterface dialog, int which) {
    	    	group.setName(input.getText().toString());
    	        ContactManager.updateGroup(group);
    	        callback.onTaskComplete();
    	    }
    	});
    	builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    	    @Override
    	    public void onClick(DialogInterface dialog, int which) {
    	        dialog.cancel();
    	    }
    	});

    	builder.show();
    }
    
    private void addMember(){
    	final List<Contact> contacts = ContactManager.getContacts();
    	
    	Collections.sort(contacts, new Comparator<Contact>(){

			@Override
			public int compare(Contact a, Contact b) {
				return a.getFirstName().compareToIgnoreCase(b.getFirstName());
			}
    		
    	});
    	
    	String[] names = new String[contacts.size()];
    	int i = 0;
    	for(Contact c : contacts){
    		names[i] = c.getFirstName() + " " + c.getLastName();
    		i++;
    	}
    	
    	final OnTaskCompleted callback = this;
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose a new member.");
        builder.setItems(names, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
                	   ContactManager.removeContactFromGroup(-2, contacts.get(which).getID());
	                   ContactManager.addContactToGroup(group.getID(), contacts.get(which).getID());
	                   callback.onTaskComplete();
               }
        });
        builder.show();
    }
    
    private void removeMember(){
    	final List<Contact> contacts = group.getMembers();
    	String[] names = new String[contacts.size()];
    	int i = 0;
    	for(Contact c : contacts){
    		names[i] = c.getFirstName() + " " + c.getLastName();
    		i++;
    	}
    	
    	final OnTaskCompleted callback = this;
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose member to remove.");
        builder.setItems(names, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int which) {
	                   ContactManager.removeContactFromGroup(group.getID(), contacts.get(which).getID());
	                   callback.onTaskComplete();
               }
        });
        builder.show();
    }
    
    private void delete(){
    	
    	
    	new AlertDialog.Builder(this)
	    .setTitle("Delete Group")
	    .setMessage("Are you sure you want to delete this group? All members will be removed.")
	    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) { 
	        	ContactManager.removeContactFromGroup(group.getID(), -2l);//-2l will remove all contacts. See contactmanager.
	        	ContactManager.removeGroupById(group.getID());
	        	
	        	Context context = getApplicationContext();
	        	CharSequence text = "Group Deleted";
	        	int duration = Toast.LENGTH_LONG;

	        	Toast toast = Toast.makeText(context, text, duration);
	        	toast.show();
	        	
	        	onBackPressed();
	        	
	        }
	     })
	    .setNegativeButton("No", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) { 
	            // do nothing
	        }
	     })
	     .show();
    }
    

	@Override
	public void onTaskComplete() {
		resetView();
	}
	

}
